<template>
  <d2-container>
    <template slot="header">
      <el-form
        :inline="true"
        :model="queryForm"
        ref="queryForm"
        size="mini"
        style="margin-bottom: -18px;"
      >
        <el-form-item label="统计区域" prop="areaName">
          <el-input
            v-model="queryForm.areaName"
            placeholder="用户"
            style="width: 100px;"
            :disabled="true"
          />
        </el-form-item>

        <el-form-item label prop="type">
          <el-select v-model="queryForm.type" placeholder="请选择" style="width: 100px;">
            <el-option
              v-for="(item, index) in queryForm.selectOption"
              :key="index"
              :label="item.valueName"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label prop="searchVal">
          <el-input v-model="queryForm.searchVal" placeholder="请输入" style="width: 100px;" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleFormSubmit">
            <d2-icon name="search" />查询
          </el-button>
        </el-form-item>
      </el-form>
    </template>
    <split-pane :min-percent="10" :max-percent="20" :default-percent="20" split="vertical">
      <template slot="paneL">
        <my-area-tree @change="onAreaChange" />
      </template>
      <template slot="paneR">
        <d2-crud
          ref="d2Crud"
          selection-row
          @selection-change="handleSelectionChange"
          :columns="columns"
          :data="data"
          :loading="loading"
          :pagination="pagination"
          @pagination-current-change="paginationCurrentChange"
          @dialog-open="handleDialogOpen"
          @dialog-cancel="handleDialogCancel"
          :form-options="formOptions"
          @row-remove="handleRowRemove"
          @customEdit="editRowFun"
          :rowHandle="rowHandle"
        >
          <!--          add-title="新增户号"-->
          <!--          :add-template="addTemplate"-->
          <!--          :add-rules="addRules"-->
          <!--          @row-add="handleRowAdd"-->
          <!--          :rowHandle="rowHandle"-->
          <!--          edit-title="修改户号"-->
          <!--          :edit-template="addTemplate"-->
          <!--          :edit-rules="addRules"-->
          <!--          @row-edit="handleRowEdit"-->
          <el-button size="mini" slot="header" style="margin-bottom: 5px" @click="addRow">新增</el-button>
          <el-button size="mini" slot="header" style="margin-bottom: 5px" @click="deleteRows">删除</el-button>
          <el-button size="mini" slot="header" style="margin-bottom: 5px">导入添加户号</el-button>
          <el-button size="mini" slot="header" style="margin-bottom: 5px">导入更新户号</el-button>
        </d2-crud>
      </template>
    </split-pane>
    <el-dialog :visible.sync="addShow" v-if="addShow" :title="title">
      <el-form
        :model="dialogForm"
        ref="dialogForm"
        size="mini"
        style="margin-bottom: -18px;width:825px"
        :rules="addRules"
        :inline-message="true"
      >
        <div class="dialogInfoBox">
          <div class="dialogInfo">
            <el-form-item label="户名" prop="householdName" label-width="110px">
              <el-input v-model="dialogForm.householdName" placeholder="请输入" style="width: 70%;" />
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="用能行业" prop="industry" label-width="110px">
              <el-select v-model="dialogForm.industry" placeholder="请选择" style="width: 70%;">
                <el-option
                  v-for="(item, index) in industryList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="计费方案" prop="paramPriceId" label-width="110px">
              <el-select v-model="dialogForm.paramPriceId" placeholder="请选择" style="width: 70%;">
                <el-option
                  v-for="(item, index) in paramPriceList"
                  :key="index"
                  :label="item.priceName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="设备信息" prop="serialnumber" label-width="110px">
              <el-autocomplete
                style="width: 70%;"
                class="inline-input"
                v-model="dialogForm.serialnumber"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                @select="handleSelect"
              ></el-autocomplete>
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="户号" prop="householdSerialnumber" label-width="110px">
              <el-input v-model="dialogForm.householdSerialnumber" disabled style="width: 70%;" />
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="所属区域" prop="areaOrgName" label-width="110px">
              <el-input v-model="dialogForm.areaOrgName" disabled style="width: 70%;" />
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="户号地址" prop="householdAddress" label-width="110px">
              <el-input v-model="dialogForm.householdAddress" style="width: 70%;" />
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="手机号码" prop="householdPhone" label-width="110px">
              <el-input v-model="dialogForm.householdPhone" style="width: 70%;" />
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="警告金额" prop="householdWarnMoney" label-width="110px">
              <el-input
                v-model="dialogForm.householdWarnMoney"
                placeholder="请输入"
                style="width: 70%;"
              />
            </el-form-item>
          </div>
          <div class="dialogInfo">
            <el-form-item label="账户余额" prop="householdFee" label-width="110px">
              <el-input v-model="dialogForm.householdFee" placeholder="请输入" style="width:70%;" />
            </el-form-item>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="title !== '编辑户号'" type="primary" @click="handleRowAdd('dialogForm')">确 定</el-button>
        <el-button v-if="title === '编辑户号'" type="primary" @click="handleRowEdit('dialogForm')">保存</el-button>
      </span>
    </el-dialog>
  </d2-container>
</template>

<script>
import util from "@/libs/util";
import MyAreaTree from "@/components/my-area-tree";
import { Divider } from "element-ui";

export default {
  name: "household",
  components: { MyAreaTree },

  data() {
    return {
      title: "",
      addShow: false,
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 100,
        total: 0
      },
      queryForm: {
        areaId: "1",
        areaName: "中国",
        type: 0,
        searchVal: "",
        selectOption: []
      },
      columns: [
        {
          title: "序号",
          key: "serialNum",
          width: 50
        },
        {
          title: "户名",
          key: "householdName",
          sortable: true
        },
        {
          title: "户号",
          key: "householdSerialnumber",
          sortable: true
        },
        {
          title: "区域组织",
          key: "areaOrgName",
          sortable: true
        },
        {
          title: "手机号码",
          key: "householdPhone",
          sortable: true
        },
        {
          title: "户号地址",
          key: "householdAddress",
          sortable: true
        }
      ],
      data: [],
      treeData: [],
      values: [],
      selectParams: {
        size: "mini"
      },
      rowHandle: {
        columnHeader: "操作",
        custom: [
          {
            text: "编辑",
            // show: true,
            type: "primary",
            size: "mini",
            emit: "customEdit",
            float: "right"
          }
        ],
        // edit: {
        //   emit: 'customEdit',
        //   text: '编辑'
        // },
        remove: {
          text: "删除"
        }
      },

      selectionRow: [],
      treeParams: {
        "default-expand-all": true,
        data: [],
        props: {
          children: "children",
          label: "name",
          value: "id"
        }
      },
      formOptions: {
        labelWidth: "80px",
        labelPosition: "left",
        saveLoading: false
      },
      dialogForm: {
        id: "",
        householdName: "", // 户名
        industry: "", // 用能行业
        serialnumber: "", // 设备信息
        paramPriceId: "", // 计费方案
        householdSerialnumber: "户号自动生成", // 户号
        areaOrgName: "", // 所属区域
        areaOrg: "", // 所属区域Id
        householdAddress: "", // 户号地址
        householdPhone: "", // 手机号码
        householdWarnMoney: "", // 警告金额
        householdFee: "" // 账户余额
      },
      industryList: [],
      paramPriceList: [],
      serialnumberList: [],
      addTemplate: {
        id: {
          title: "id",
          value: "",
          component: {
            show: false
          }
        },
        householdName: {
          title: "户名",
          value: ""
        },
        industry: {
          title: "用能行业",
          value: "",
          component: {
            name: "el-select",
            multiple: false,
            options: []
          }
        },
        householdSerialnumber: {
          title: "户号",
          value: "户号自动生成",
          component: {
            disabled: true
          }
        },
        areaOrgName: {
          title: "所属区域",
          value: "",
          component: {
            disabled: true
          }
        },
        areaOrg: {
          title: "所属区域Id",
          value: "",
          component: {
            show: false
          }
        },
        householdAddress: {
          title: "户号地址",
          value: ""
        },
        householdPhone: {
          title: "手机号码",
          value: ""
        },
        // householdPassword: {
        //   title: "登录密码",
        //   value: ""
        // },
        householdWarnMoney: {
          title: "警告金额",
          value: 100
        },
        householdFee: {
          title: "账户余额",
          value: ""
        }
      },
      addRules: {
        householdName: [
          { required: true, message: "请输入户名", trigger: "blur" }
        ],
        householdAddress: [
          { required: true, message: "请输入户号地址", trigger: "blur" }
        ],
        industry: [
          { required: true, message: "请选择用能行业", trigger: "blur" }
        ],
        paramPriceId: [
          { required: true, message: "请选择计费方案", trigger: "blur" }
        ],
        serialnumber: [
          { required: true, message: "请选择设备信息", trigger: "blur" }
        ],
        householdPhone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, message: "手机号码格式有误" }
        ],
        // householdPassword: [
        //   { required: true, message: "请输入登录密码", trigger: "blur" }
        // ],
        householdWarnMoney: [
          { required: true, message: "请输入警告金额", trigger: "blur" },
          {
            pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/,
            message: "警告金额大于0"
          }
        ],
        householdFee: [
          { required: true, message: "请输入账户余额", trigger: "blur" },
          {
            pattern: /^(\-|\+)?\d+(\.\d+)?$/,
            message: "请输入数字"
          }
        ]
      }
    };
  },
  watch: {
    "dialogForm.industry"(val, oldValue) {
      if (val == oldValue) return;
      this.getPriceGetList(val);
    }
  },
  mounted() {
    this.getEquipConcentVOList();
    this.getEquipmentType();
    this.getEnergyIndustry();
    this.fetchData();
  },
  methods: {
    handleSelect(item) {
      this.serialnumber = item.id;
    },
    querySearch(queryString, cb) {
      const restaurants = this.serialnumberList;
      const results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelectionChange(selection) {
      console.log(selection);
      this.selectionRow = selection;
    },
    deleteRows() {
      console.log(this.selectionRow);
      this.$confirm("确定删除吗?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error"
      }).then(() => {
        this.$api
          .admin_household_delete(this.selectionRow.map(item => item.id))
          .then(res => {
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.fetchData();
          });
      });
    },
    // 删除row数据
    handleRowRemove({ index, row }, done) {
      this.$api.admin_household_delete([row.id]).then(res => {
        this.$message({
          message: "删除成功",
          type: "success"
        });
        this.fetchData();
        done();
      });
    },
    handleDialogOpen({ mode, row, index }) {
      console.log(mode, row);
      if (mode === "edit") {
        this.$api.admin_household_get({ id: row.id }).then(res => {
          this.$refs.d2Crud.setFormData(res);
        });
      }
    },
    // 增加row数据
    handleRowEdit(row, done) {
      this.$refs['dialogForm'].validate(valid => {
        if (valid) {
          this.formOptions.saveLoading = true;
          this.$api
            // .admin_household_update(row.row)
            .admin_household_update(this.dialogForm)
            .then(res => {
              this.$message({
                message: "保存成功",
                type: "success"
              });
              this.addShow = false;
              this.handleFormSubmit();
              console.log(this.addShow);
              // done()
            })
            .finally(() => {
              this.formOptions.saveLoading = false;
            });
        }
      });
    },
    // 关闭弹框
    handleDialogCancel(done) {
      done();
    },
    // 获取用能行业列表
    getEnergyIndustry() {
      this.$api
        .admin_energyIndustry_getEnergyIndustry()
        .then(res => {
          const options = res.map(y => {
            return {
              value: y.id,
              label: y.name
            };
          });
          this.industryList = options;
          console.log(res);
        })
        .finally(() => {});
    },
    // 获取计费方案
    async getPriceGetList(id) {
      this.$api
        .admin_price_getList({ industryId: id })
        .then(res => {
          this.paramPriceList = res;
          this.dialogForm.paramPriceId = "";
          console.log(res);
        })
        .finally(() => {});
    },
    async editRowFun(data) {
      this.title = "编辑户号";
      this.addShow = true;
      const row = data.row;
      let industry = { value: "" };
      let price = { id: "" };
      if (row.industryName) {
        industry = this.industryList.find(f => f.label === row.industryName);
      }
      if (row.paramPriceName) {
        price = this.paramPriceList.find(
          f => f.priceName === row.paramPriceName
        );
      }
      // this.getPriceGetList(industry.value)
      this.dialogForm.industry = industry.value; // 用能行业
      setTimeout(() => {
        this.dialogForm = {
          id: row.id,
          householdName: row.householdName, // 户名
          industry: industry.value, // 用能行业
          serialnumber: row.serialnumber, // 设备信息
          paramPriceId: price.id ? price.id : "", // 计费方案
          householdSerialnumber: row.householdSerialnumber, // 户号
          areaOrgName: row.areaOrgName, // 所属区域
          areaOrg: row.areaOrg, // 所属区域Id
          householdAddress: row.householdAddress, // 户号地址
          householdPhone: row.householdPhone, // 手机号码
          householdWarnMoney: row.householdWarnMoney, // 警告金额
          householdFee: row.householdFee // 账户余额
        };
      }, 2000);
    },

    // 获取设备信息
    getEquipConcentVOList() {
      this.$api
        .admin_concent_getEquipConcentVOList({ serialnumber: "" })
        .then(res => {
          this.serialnumberList = res.map(r => {
            return {
              value: r.serialNumber,
              id: r.serialNumber
            };
          });
        })
        .finally(() => {
          // this.formOptions.saveLoading = false
        });
    },

    // 新增数据
    addRow() {
      this.addShow = true;
      this.title = "新增户号";
      this.dialogForm = {
        id: "",
        householdName: "", // 户名
        industry: "", // 用能行业
        paramPriceId: "", // 计费方案
        householdSerialnumber: "户号自动生成", // 户号
        areaOrgName: "", // 所属区域
        areaOrg: "", // 所属区域Id
        householdAddress: "", // 户号地址
        householdPhone: "", // 手机号码
        householdWarnMoney: "", // 警告金额
        householdFee: "" // 账户余额
      };
      this.dialogForm.areaOrg = this.queryForm.areaId;
      this.dialogForm.areaOrgName = this.queryForm.areaName;
      // this.$refs.d2Crud.showDialog({
      //   mode: 'add'
      // })
      // console.log(this.addTemplate)
      // // this.addTemplate.areaOrg.value = this.queryForm.areaId;
      // // this.addTemplate.areaOrgName.value = this.queryForm.areaName;
      // const templateObj = {}
      // templateObj.id = ''
      // templateObj.householdName = ''
      // templateObj.householdSerialnumber = '后端自动生成'
      // templateObj.areaOrg = this.queryForm.areaId
      // templateObj.areaOrgName = this.queryForm.areaName
      // templateObj.householdAddress = ''
      // templateObj.householdPhone = ''
      // templateObj.householdPassword = ''
      // templateObj.householdWarnMoney = ''
      // templateObj.householdFee = ''
      // this.$refs.d2Crud.setFormData(templateObj)
    },
    handleRowAdd(row, done) {
      this.$refs['dialogForm'].validate(valid => {
        if (valid) {
          this.formOptions.saveLoading = true;

          this.$api
            .admin_household_add(this.dialogForm)
            .then(res => {
              this.$message({
                message: "保存成功",
                type: "success"
              });
              this.handleFormSubmit();
              this.addShow = false;
              // done()
            })
            .finally(() => {
              this.formOptions.saveLoading = false;
            });
        }
      });
    },
    // 获取查询枚举
    getEquipmentType() {
      this.$api
        .admin_household_getEquipmentType()
        .then(res => {
          console.log(res);
          this.queryForm.selectOption = res.household;
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {});
    },
    // 分页操作
    paginationCurrentChange(currentPage) {
      this.pagination.currentPage = currentPage;
      this.fetchData();
    },
    onAreaChange(data, node) {
      this.queryForm.areaId = data.id;
      this.queryForm.areaName = data.name;
      this.fetchData();
    },
    fetchData() {
      this.loading = true;
      this.$api
        .admin_household_getPageList({
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          areaOrg: this.queryForm.areaId,
          filterType: this.queryForm.type,
          filterValue: this.queryForm.searchVal
        })
        .then(res => {
          this.data = res.data;
          this.pagination.total = res.total;
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleFormSubmit() {
      this.pagination.currentPage = 1;
      this.fetchData();
    }
  }
};
</script>
